Создаем свою первую базу данных на Tarantool | Tarantool
Документация на русском языке
поддерживается сообществом
Примеры и руководства Создаем свою первую базу данных на Tarantool

Создаем свою первую базу данных на Tarantool

First, let’s install Tarantool, start it, and create a simple database.

Вы можете установить Tarantool и работать с ним либо локально, либо в Docker – как вам удобнее.

For trial and test purposes, we recommend using the official Tarantool images for Docker. An official image contains a particular Tarantool version and all popular external modules for Tarantool. Everything is already installed and configured in Linux. These images are the easiest way to install and use Tarantool.

Примечание

Если вы никогда раньше не работали с Docker, рекомендуем сперва прочитать эту обучающую статью.

Если Docker не установлен на вашей машине, следуйте официальным инструкциям по установке для вашей ОС.

To start a fully functional Tarantool instance, run a container with some minimal options:

$ docker run \
  --name mytarantool \
  -d -p 3301:3301 \
  -v /data/dir/on/host:/var/lib/tarantool \
  tarantool/tarantool:latest

Эта команда запускает новый контейнер с именем mytarantool. Docker запускает его из официального образа tarantool/tarantool:latest с предустановленной последней версией Tarantool и всеми внешними модулями.

Tarantool будет принимать входящие подключения по адресу localhost:3301. Вы сразу можете начать пользоваться Tarantool как хранилищем данных типа «ключ-значение».

Tarantool хранит данные персистентно внутри контейнера. Чтобы тестовые данные оставались доступны после остановки контейнера, эта команда также монтирует директорию хоста /data/dir/on/host (следует заменить на абсолютный путь к существующей локальной директории) в директорию /var/lib/tarantool внутри контейнера. Tarantool, развернутый в контейнере, использует директорию /var/lib/tarantool, чтобы обеспечить персистентность данных. Таким образом, все изменения в директории, смонтированной внутри контейнера, попадают на диск хоста.

Tarantool’s database module in the container is already configured and started. You don’t need to do it manually, unless you use Tarantool as an application server and run it with an application.

Примечание

If your container terminates immediately after starting, follow this page for a possible solution.

Чтобы подключиться к Tarantool, работающему в контейнере, выполните:

$ docker exec -i -t mytarantool console

Эта команда:

  • Дает Tarantool команду открыть порт с интерактивной консолью для входящих подключений.
  • Attaches to the Tarantool server inside the container under the admin user via a standard Unix socket.

Tarantool показывает приглашение командной строки:

tarantool.sock>

Теперь вы можете вводить запросы в командной строке.

Примечание

On production machines, Tarantool’s interactive mode is designed for system administration only. We use it for most examples in this manual, because it is convenient for learning.

While we’re attached to the console, let’s create a simple test database.

Сначала создайте первый спейс (с именем tester):

tarantool.sock> s = box.schema.space.create('tester')

Форматируйте созданный спейс, указывая имена и типы полей:

tarantool.sock> s:format({
              > {name = 'id', type = 'unsigned'},
              > {name = 'band_name', type = 'string'},
              > {name = 'year', type = 'unsigned'}
              > })

Создайте первый индекс (с именем primary):

tarantool.sock> s:create_index('primary', {
              > type = 'tree',
              > parts = {'id'}
              > })

Это первичный индекс по полю id в каждом кортеже. Тип индекса TREE — самый универсальный. Подробная информация изложена в документации о типах индексов в Tarantool.

Вставьте в созданный спейс три кортежа (наш термин для записей):

tarantool.sock> s:insert{1, 'Roxette', 1986}
tarantool.sock> s:insert{2, 'Scorpions', 2015}
tarantool.sock> s:insert{3, 'Ace of Base', 1993}

To select a tuple using the primary index, run:

tarantool.sock> s:select{3}

Теперь вывод в окне терминала выглядит следующим образом:

tarantool.sock> s = box.schema.space.create('tester')
---
...
tarantool.sock> s:format({
              > {name = 'id', type = 'unsigned'},
              > {name = 'band_name', type = 'string'},
              > {name = 'year', type = 'unsigned'}
              > })
---
...
tarantool.sock> s:create_index('primary', {
              > type = 'tree',
              > parts = {'id'}
              > })
---
- unique: true
  parts:
  - type: unsigned
    is_nullable: false
    fieldno: 1
  id: 0
  space_id: 512
  name: primary
  type: TREE
...
tarantool.sock> s:insert{1, 'Roxette', 1986}
---
- [1, 'Roxette', 1986]
...
tarantool.sock> s:insert{2, 'Scorpions', 2015}
---
- [2, 'Scorpions', 2015]
...
tarantool.sock> s:insert{3, 'Ace of Base', 1993}
---
- [3, 'Ace of Base', 1993]
...
tarantool.sock> s:select{3}
---
- - [3, 'Ace of Base', 1993]
...

To add a secondary index based on the band_name field, run:

tarantool.sock> s:create_index('secondary', {
              > type = 'tree',
              > parts = {'band_name'}
              > })

To select tuples using the secondary index, run:

tarantool.sock> s.index.secondary:select{'Scorpions'}
---
- - [2, 'Scorpions', 2015]
...

To drop an index, run:

tarantool> s.index.secondary:drop()
---
...

После завершения тестирования для корректной остановки контейнера выполните эту команду:

$ docker stop mytarantool

This was a temporary container, and its disk/memory data were flushed when you stopped it. But since you mounted a data directory from the host in the container, Tarantool’s data files were persisted to the host’s disk. Now if you start a new container and mount that data directory, Tarantool will recover all of the data from disk and continue working with the persisted data.

For production purposes, we recommend that you install Tarantool via the official package manager. You can choose one of three versions: LTS, stable, or beta. An automatic build system creates, tests and publishes packages for every push into a corresponding branch at Tarantool’s GitHub repository.

Чтобы скачать и установить подходящий пакет, откройте командную строку и введите инструкции, которые даны для вашей операционной системы на странице для скачивания.

To start working with Tarantool, start a terminal and run this:

$ tarantool
$ # при этом создается новый экземпляр Tarantool

Tarantool starts in interactive mode and displays a prompt:

tarantool>

Теперь вы можете вводить запросы в командной строке.

Примечание

On production machines, Tarantool’s interactive mode is designed for system administration only. We use it for most examples in this manual because it is convenient for learning.

Далее объясняется, как создать простую тестовую базу данных после установки Tarantool.

  1. Чтобы Tarantool хранил данные в определенном месте, создайте предназначенную специально для тестов директорию:

    $ mkdir ~/tarantool_sandbox
    $ cd ~/tarantool_sandbox
    

    You can delete the directory when the tests are completed.

  2. Check if the default port that the database instance will listen to is vacant.

    Пакеты Tarantool для Debian и Ubuntu до версии 2.4.2 во время установки автоматически активируют и запускают демонстрационный экземпляр example.lua, который по умолчанию слушает порт 3301. Файл example.lua с базовой конфигурацией можно найти в директории /etc/tarantool/instances.enabled или /etc/tarantool/instances.available.

    Тем не менее, мы предлагаем провести установку самостоятельно с целью обучения.

    Убедитесь, что свободен порт, используемый по умолчанию:

    1. To check if the demonstrative instance is running, run:

      $ lsof -i :3301
      COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
      tarantool 6851 root   12u  IPv4  40827      0t0  TCP *:3301 (LISTEN)
      
    2. If it is running, kill the corresponding process. In this example:

      $ kill 6851
      
  3. To start Tarantool’s database module and make the instance accept TCP requests on port 3301, run:

    tarantool> box.cfg{listen = 3301}
    
  4. Создайте первый спейс (с именем tester):

    tarantool> s = box.schema.space.create('tester')
    
  5. Форматируйте созданный спейс, указывая имена и типы полей:

    tarantool> s:format({
             > {name = 'id', type = 'unsigned'},
             > {name = 'band_name', type = 'string'},
             > {name = 'year', type = 'unsigned'}
             > })
    
  6. Создайте первый индекс (с именем primary):

    tarantool> s:create_index('primary', {
             > type = 'tree',
             > parts = {'id'}
             > })
    

    Это первичный индекс по полю id в каждом кортеже. Тип индекса TREE — самый универсальный. Подробная информация изложена в документации о типах индексов в Tarantool.

  7. Вставьте в созданный спейс три кортежа (наш термин для записей):

    tarantool> s:insert{1, 'Roxette', 1986}
    tarantool> s:insert{2, 'Scorpions', 2015}
    tarantool> s:insert{3, 'Ace of Base', 1993}
    
  8. To select a tuple using the primary index, run:

    tarantool> s:select{3}
    

    Теперь вывод в окне терминала выглядит следующим образом:

    tarantool> s = box.schema.space.create('tester')
    ---
    ...
    tarantool> s:format({
             > {name = 'id', type = 'unsigned'},
             > {name = 'band_name', type = 'string'},
             > {name = 'year', type = 'unsigned'}
             > })
    ---
    ...
    tarantool> s:create_index('primary', {
             > type = 'tree',
             > parts = {'id'}
             > })
    ---
    - unique: true
      parts:
      - type: unsigned
        is_nullable: false
        fieldno: 1
      id: 0
      space_id: 512
      name: primary
      type: TREE
    ...
    tarantool> s:insert{1, 'Roxette', 1986}
    ---
    - [1, 'Roxette', 1986]
    ...
    tarantool> s:insert{2, 'Scorpions', 2015}
    ---
    - [2, 'Scorpions', 2015]
    ...
    tarantool> s:insert{3, 'Ace of Base', 1993}
    ---
    - [3, 'Ace of Base', 1993]
    ...
    tarantool> s:select{3}
    ---
    - - [3, 'Ace of Base', 1993]
    ...
    
  9. To add a secondary index based on the band_name field, run:

    tarantool> s:create_index('secondary', {
             > type = 'tree',
             > parts = {'band_name'}
             > })
    
  10. To select tuples using the secondary index, run:

    tarantool> s.index.secondary:select{'Scorpions'}
    ---
    - - [2, 'Scorpions', 2015]
    ...
    
  11. Теперь, чтобы подготовиться к примеру в следующем разделе, попробуйте следующее:

    tarantool> box.schema.user.grant('guest', 'read,write,execute', 'universe')
    

В запросе box.cfg{listen = 3301}, который мы отправили ранее, параметр listen может принимать в качестве значения URI (унифицированный идентификатор ресурса) любой формы. В нашем случае это просто локальный порт 3301. Вы можете отправлять запросы на указанный URI, используя:

  1. telnet,
  2. коннектор,
  3. другой экземпляр Tarantool (с помощью модуля console),
  4. tt administrative utility.

Давайте попробуем (3) способ.

Переключитесь на другой терминал. Например, в Linux-системе для этого нужно запустить еще один экземпляр Bash. В новом терминале можно сменить текущую рабочую директорию на любую другую, необязательно использовать ~/tarantool_sandbox.

Запустите еще один экземпляр tarantool:

$ tarantool

Используйте net.box, чтобы подключиться к экземпляру Tarantool, который слушает по адресу localhost:3301»:

tarantool> net_box = require('net.box')
---
...
tarantool> conn = net_box.connect(3301)
---
...

Введите следующий запрос:

tarantool> conn.space.tester:select{2}

Это означает «отправить запрос тому экземпляру Tarantool и вывести результат на экран». Сам запрос аналогичен запросу box.space.tester:select{2} к локальному экземпляру. Результатом в данном случае будет один из кортежей, что вы вставляли ранее. В окне терминала теперь должно отображаться примерно следующее:

$ tarantool

Tarantool 2.6.1-32-g53dbba7c2
type 'help' for interactive help
tarantool> net_box = require('net.box')
---
...
tarantool> conn = net_box.connect(3301)
---
...
tarantool> conn.space.tester:select{2}
---
- - [2, 'Scorpions', 2015]
...

Можно посылать запросы box.space...:insert{} and box.space...:select{} (или же conn.space...:insert{} и conn.space...:select{}) неограниченное количество раз на любом из двух экземпляров Tarantool.

Закончив тестирование, выполните следующие шаги:

  • Для удаления спейса: s:drop()
  • Для остановки tarantool: Ctrl+C или Ctrl+D
  • Чтобы остановить Tarantool (другой способ): стандартная Lua-функция os.exit()
  • Для остановки Tarantool (из другого терминала): sudo pkill -f tarantool
  • Для удаления директории-песочницы: rm -r ~/tarantool_sandbox
Нашли ответ на свой вопрос?
Обратная связь